<?php
/**
 * Created by PhpStorm.
 * User: meng
 * Date: 2023/9/15
 * Time: 14:29
 */

namespace lib\common;

use lib\utils\CacheUtils;
use think\facade\Db;
use Webman\Config;

class CommonService
{
    public bool $enableCache = false;

    public function __construct () {
        $this->enableCache = Config::get('admin.cache_enable', false);
    }

    public function flushCache (): bool {
        return CacheUtils::flush();
    }

    /**
     * @param array|int|string|null $params
     * @param string $name
     * @param int|null $maxSize
     * @param int|null $defaultSize
     * @return int
     */
    protected function getPageSize (mixed $params = null, string $name = 'limit', int $maxSize = null, int $defaultSize = null): int {
        $defaultSize = empty($defaultSize) ? Config::get('admin.page_default_size') : $defaultSize;
        $maxSize = empty($maxSize) ? Config::get('admin.page_max_size') : $maxSize;
        $limit = null;
        if (is_string($params) || is_numeric($params)) {
            $limit = intval($params);
        } else if (is_array($params)) {
            $limit = empty($params[$name]) ? (int) request()->input($name, 0) : intval($params[$name]);
        } else if (is_null($params)) {
            $limit = (int) request()->input($name, 0);
        }
        $limit = empty($limit) || $limit <= 0 ? $defaultSize : $limit;
        return min($limit, $maxSize);
    }

    /**
     * 数据库事务操作
     * @param callable $closure
     * @param bool $isTran
     * @return mixed
     */
    public function transaction(callable $closure, bool $isTran = true) {
        return $isTran ? Db::transaction($closure) : $closure();
    }

    /**
     * 开启事务
     */
    public function startTrans (): void {
        Db::startTrans();
    }

    /**
     * 提交事务
     */
    public function commit (): void {
        Db::commit();
    }

    /**
     * 回滚事务
     */
    public function rollback (): void {
        Db::rollback();
    }
}
